#!/usr/bin/perl

# Here we have five conditions
# reach maxconn | http react | http fail | vip in | vip out

my @out = "";
my @out_unorder = "";
my @out_order = "";
my $count = 0;
my $counter = ();
my $saida = ();
my %hash = ();
my $exists;

my $logfile = "/export/logs/slb_alarms2.log" ;

sub runLogger 
{
   my $line = shift ();
   `$logger -p local5.info "$line"`;

   open ( LOG, ">>$logfile" ) or die "Can't open $logfile: $!\n" ;
   print LOG "$line";
   close (LOG);
   print "$line\n";
}


$file = "slbalarm.cache";
$logger="/bin/logger";
$now=time;

while ( <STDIN> )
{
 chop;
 @line = split (/\s|\t/,"$_");
  @line = @line[15,16,17,18,19,20,21,22,23,24,25,26];
  $firstfield = shift(@line);
  if ( $firstfield =~ /^server/ ) {
   # reach maxconn 
   #print "@line\n";
   $error = "$line[3] $line[5] $line[7] to $line[0]\n";
   push (@out, "$error");
  }   
  elsif ($firstfield =~ /^SLB/) {
    if ($line[3] =~ /activated/ ) {
     # http reactivated
     #print "@line\n";
    }
    if ($line[3] =~ /failed/ ) {
     # http failed
     #print "@line\n";
     $error = "$line[9] $line[2] $line[3] to $line[6]\n";
     push (@out, "$error");
    }
  }
  else {
   if ($line[0] eq "inservice" ) {
    # vip in service
    #print "$firstfield @line\n";
   }
   else {
    # vip out of service
    #print "$firstfield @line\n";
   }
  }
     foreach (@out) {
        $count++;
        #print "$count\n";
        chomp;
        my ($farm, $value, $status, $nop2, $ipaddr) = split(/\s/,$_);
        #print "|$farm, $value, $status, $nop2, $ipaddr|\n";


        $counter->{$farm}->{$ipaddr}++;   
        if ($counter->{$farm}->{$ipaddr} > 10){
           $counter->{$farm}->{$ipaddr} = "";

              foreach (@out_order) {
                 if ($saida->{$farm}->{$ipaddr} = $_) {
                    $exists = 1;
                 }
              }
              if ($exists eq "1" || $farm eq "\'SEDNA110FARM\'" || $farm eq "SEDNA143FARM\'") {
                 next;
              }
              else {
                 push (@out_unorder, "$_");
                 #print qq^push $farm $ipaddr\n^;
              }
        }

        if ($count > 50) {
           $counter = ();
           $count = 0;
           @hash{@out_unorder} = @out_unorder;
           for (keys %hash) { push (@out_order, "$_\n"); }
           @out_order = sort(@out_order);
           #print "$#out_order\n";

           if ($#out_order <= "1"){
              #print "ciclo -> OK\n";
              my $now = time ;
              runLogger("[$now] PROCESS_SERVICE_CHECK_RESULT;zula1;SLB Alarm;0;Servidor OK\n");
           }
           else {
              #print "ciclo -> FAIL -> @out_order\n";
              my $now = time ;
              runLogger("[$now] PROCESS_SERVICE_CHECK_RESULT;zula1;SLB alarm;1;@out_order\n");
           }

          $saida = ();
          $counter = ();
          @out_unorder = "";
          @out_order = "";
        }
     }



}
